// 云函数入口文件
const cloud = require("wx-server-sdk");
cloud.init();
const db = cloud.database();

async function isExist(openId) {
    const $ = db.command;
    const { list } = await db
        .collection("User")
        .aggregate()
        .match({
            openId: $.eq(openId),
        })
        .limit(1)
        .end();

    return list;
}
exports.main = async ({ userInfo, USERINFO }) => {
    let list = await isExist(userInfo.openId);
    // 未查询到数据
    if (list.length === 0) {
        if (USERINFO) {
            // 第一次申请
            const data = {
                ...userInfo,
                ...USERINFO,
                isManager: false,
                _id: userInfo.openId,
            };
            await db.collection("User").add({
                data,
            });
            const UserInfoObject = {
                likeArray: [],
                _openid: userInfo.openId,
                _id: userInfo.openId,
            };
            await db.collection("UserInfo").add({
                data: UserInfoObject,
            });
            return { ...data, UserInfo: UserInfoObject };
        } else {
            return { state: "none" };
        }
    }
    return db
        .collection("UserInfo")
        .doc(userInfo.openId)
        .get()
        .then((res) => {
            return { ...list[0], UserInfo: res.data };
        });
};
